package com.enjoy.mjbaseframe.okgo;

import android.text.TextUtils;
import android.util.Log;

import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONObject;

/**
 * Created by Administrator on 2018/1/29.
 */

public class JsonCallback<T> extends StringCallback {

    @Override
    public void onSuccess(Response<String> response) {
        try {
            String msg = response.body();
            JSONObject jsonObject = new JSONObject(msg);
            int status = jsonObject.getInt("code");
            int totalPage=0;
            if (jsonObject.has("totalPageNum")) {
                totalPage=jsonObject.getInt("totalPageNum");
            }
            Log.e("JsonCallback","返回："+msg+"code:"+status+":"+totalPage);
            switch (status){
                case 200: //状态码200
                    String result = jsonObject.getString("result");
                    Log.e("okres:",result);
                    if(TextUtils.isEmpty(result) && jsonObject.has("msg")){
                        result = jsonObject.getString("msg");
                    }
                    onComplete(result,totalPage+"");

                    break;

                default: //其他状态码
                    String message = jsonObject.getString("msg");
                    onFailure(status,message);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            onAbnormal();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            onAbnormal();
        }
    }

    /*成功状态吗*/
    public void onComplete(String body,String totalPageNum){};
    /*失败(非成功)状态吗*/
    public void onFailure(int status,String msg){};
    /*网络异常*/
    public void onAbnormal(){};

    @Override
    public void onError(Response<String> response) {
        super.onError(response);
        onAbnormal();
    }

    @Override
    public void onFinish() {
        super.onFinish();
    }
}
